<template>
  <div class="file-writer">
    <h3>文件写入工具</h3>

    <!-- 文件路径输入框 + 选择按钮 -->
    <div class="input-group">
      <el-input v-model="filePath" placeholder="请选择文件保存路径" readonly />
      <el-button @click="selectFilePath">选择路径</el-button>
    </div>

    <!-- 内容输入框 -->
    <el-input
      v-model="fileContent"
      placeholder="请输入要写入的内容..."
      :rows="10"
      type="textarea"
    ></el-input>

    <!-- 操作按钮 -->
    <div class="btn-group">
      <el-button @click="saveToFile">保存文件</el-button>
      <el-button @click="clearAll">清空</el-button>
    </div>

    <!-- 结果提示 -->
    <div v-if="message" :class="['message', messageType]">
      {{ message }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// 响应式变量
const filePath = ref('') // 保存文件路径
const fileContent = ref('') // 要写入的内容
const message = ref('') // 提示消息
const messageType = ref('info') // 消息类型：success/error/info

// 选择文件保存路径（调用系统对话框）
const selectFilePath = async () => {
  try {
    const result = await window.electronAPI.showSaveDialog()
    if (!result.canceled && result.filePaths) {
      filePath.value = result.filePaths[0]
      message.value = `已选择路径：${result.filePaths[0]}`
      messageType.value = 'info'
    }
  } catch (err) {
    message.value = `选择路径失败：${err}`
    messageType.value = 'error'
  }
}

// 写入文件（调用主进程的写入逻辑）
const saveToFile = async () => {
  if (!filePath.value) return
  if (!fileContent.value.trim()) {
    message.value = '内容不能为空！'
    messageType.value = 'error'
    return
  }

  try {
    const res = await window.electronAPI.writeFile(filePath.value, fileContent.value)
    message.value = res.message
    messageType.value = res.success ? 'success' : 'error'
  } catch (err) {
    message.value = `保存失败：${err}`
    messageType.value = 'error'
  }
}

// 清空输入
const clearAll = () => {
  filePath.value = ''
  fileContent.value = ''
  message.value = ''
}
</script>

<style scoped>
.file-writer {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-top: 12px;
  margin-bottom: 15px;
}

.input-group input {
  flex: 1;
  padding: 8px;
}

textarea {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  resize: vertical;
}

.btn-group {
  display: flex;
  gap: 10px;
  margin-top: 12px;
  margin-bottom: 15px;
}

button {
  padding: 8px 16px;
  cursor: pointer;
}

.btn-group button:first-child {
  background: #409eff;
  color: white;
  border: none;
}

.message {
  padding: 10px;
  border-radius: 4px;
}

.success {
  background: #f0f9eb;
  color: #52c41a;
}

.error {
  background: #fef3f2;
  color: #f5222d;
}

.info {
  background: #f0f2f5;
  color: #1890ff;
}
</style>
